<!--  -->
<template>
    <div class=''>
        <!-- 面包屑导航区，图标分隔符 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品参数</el-breadcrumb-item>
            </el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <el-alert type="warning" title="注意：只允许为第三级分类设置相关参数" :closable="false" show-icon></el-alert>

            <!-- 选择商品分类区 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                </el-col>
                <!-- option指定数据源 -->
                <!-- props用来指定配置对象 -->
                <!-- change-on-select 是否允许选择任意一级选项 -->
                <el-cascader :options="cateList" :props="cateProps" v-model="selectedKeys" expand-trigger="hover"
                    @change="handleChange">
                </el-cascader>
            </el-row>

            <!-- tab页标签区 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 添加动态参数 -->
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加参数
                    </el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableData" border stripe>
                        <!-- 索引列 -->
                        <el-table-column label="#" type="index"></el-table-column>
                        <!-- 展开列 -->
                        <el-table-column label="" type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable 
                                @close="handleClose(i,scope.row)">{{item}}</el-tag>
                                <!-- 输入文本框 -->
                                <el-input class="input-new-tag"
                                 v-if="scope.row.inputVisible" v-model="scope.row.inputValue" 
                                 size="small"
                                 @keyup.enter.native="handleInputConfirm(scope.row)"
                                 @blur="handleInputConfirm(scope.row)"
                                 ref="saveTagInput"></el-input>
                                <!-- 添加按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit"
                                    @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 添加静态属性面板 -->
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性
                    </el-button>
                    <!-- 静态参数表格 -->
                    <el-table :data="onlyTableData" border stripe>
                        <!-- 索引列 -->
                        <el-table-column label="#" type="index"></el-table-column>
                        <!-- 展开列 -->
                        <el-table-column label="" type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable 
                                @close="handleClose(i,scope.row)">{{item}}</el-tag>
                                <!-- 输入文本框 -->
                                <el-input class="input-new-tag"
                                 v-if="scope.row.inputVisible" v-model="scope.row.inputValue" 
                                 size="small"
                                 @keyup.enter.native="handleInputConfirm(scope.row)"
                                 @blur="handleInputConfirm(scope.row)"
                                 ref="saveTagInput"></el-input>
                                <!-- 添加按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit"
                                    @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加参数的对话框 -->
        <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <el-form :model="addForm" ref="addForm" :rules="addFormRules">
                <el-form-item :label="titleText" prop="attr_name" label-width="80px">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="addParams">确定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑参数的对话框 -->
        <el-dialog :title="'编辑'+titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <el-form :model="editForm" ref="editForm" :rules="editFormRules">
                <el-form-item :label="titleText" prop="attr_name" label-width="80px">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="editParams">确定</el-button>
            </span>
        </el-dialog>


    </div>
</template>

<script>
    //这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
    //例如：import 《组件名称》 from '《组件路径》';

    export default {
        //import引入的组件需要注入到对象中才能使用
        name: 'Params',
        components: {},
        props: {},
        data() {
            //这里存放数据
            return {
                cateList: [],//所有分类数据
                cateProps: {
                    value: 'cat_id',//指定选中的值
                    label: 'cat_name',//指定看到的值
                    children: 'children',
                },//指定级联选择器的配置对象
                //级联选择框双向绑定的数组
                selectedKeys: [],
                activeName: 'many',//默认展示的页签
                manyTableData: [],//动态参数
                onlyTableData: [],//静态属性    
                addDialogVisible: false,//控制添加对话框的显示/隐藏
                addForm: {},//添加参数的表单数据对象
                editForm: {},//
                addFormRules: {
                    attr_name: [
                        { required: true, message: '参数名称', trigger: 'blur' }
                    ]
                },//添加表单的规则验证
                editFormRules: {
                    attr_name: [
                        { required: true, message: '参数名称', trigger: 'blur' }
                    ]
                },
                editDialogVisible: false,//控制修改对话框的显示/隐藏
            };
        },
        //监听属性 类似于data概念
        computed: {
            //如果按钮需要被禁用，返回true，否则返回false
            isBtnDisabled() {
                if (this.selectedKeys.length !== 3) {
                    return true;
                }
                return false;
            },

            //当前选中的三级分类的id
            cateId() {
                if (this.selectedKeys.length === 3) {
                    return this.selectedKeys[2];
                }
                return null;
            },

            //动态计算标题文本
            titleText() {
                if (this.activeName === 'many') {
                    return '动态参数'
                }
                return '静态属性'
            },
        },
        //监控data中的数据变化
        watch: {},
        //方法集合
        methods: {
            //获取所有商品分类列表
            async getCateList() {
                const { data: res } = await this.$http.get('categories');
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
                this.cateList = res.data;
                // console.log(res);
            },

            //级联选择框选中项改变触发的函数
            async handleChange() {
                this.getParamData();
            },

            //获取参数方法
            async getParamData() {
                //如果选中的不是3级分类，重置选项
                if (this.selectedKeys.length !== 3) {
                    this.selectedKeys = [];
                    this.manyTableData=[];
                    this.onlyTableData=[];
                    return;
                }
                //根据所选分类的id，和当前所处的面板，获取对应的参数
                const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', { params: { sel: this.activeName } });
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
                // console.log(res);

                res.data.forEach(item=>{
                    //如果为空，返回空数组
                    item.attr_vals=item.attr_vals?item.attr_vals.split(' '):[];
                    //控制文本框的显示与隐藏
                    item.inputVisible=false;
                    //文本框中输入的值
                    item.inputValue='';
                })

                // console.log(res.data);

                if (this.activeName === 'many') {
                    this.manyTableData = res.data;//给动态参数赋值
                } else {
                    this.onlyTableData = res.data;//给静态属性赋值
                }
            },

            //tab页签点击事件处理
            handleTabClick() {
                this.getParamData();
            },

            //监听添加对话框的关闭事件
            addDialogClosed() {
                this.$refs.addForm.resetFields();
            },

            //监听修改对话框的关闭事件
            editDialogClosed() {
                this.$refs.editForm.resetFields();
            },

            //点击按钮添加参数
            addParams() {
                console.log(this.addForm);
                this.$refs.addForm.validate(async value => {
                    if (!value) return;
                    const { data: res } = await this.$http.post('categories/' + this.cateId + '/attributes', {
                        attr_name: this.addForm.attr_name,
                        attr_sel: this.activeName
                    });
                    if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
                    // console.log(res);
                    this.addDialogVisible = false;
                    this.getParamData();//刷新数据
                    this.$message.success(res.meta.msg);

                })
            },

            //点击按钮展示编辑的对话框
            async showEditDialog(attr_id) {
                const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes/' + attr_id, {
                    params: { attr_sel: this.activeName }
                });
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg);

                this.editDialogVisible = true;
                this.editForm = res.data;
            },

            //点击按钮修改参数
            editParams() {
                this.$refs.editForm.validate(async value=>{
                    if(!value) return
                    const { data: res } = await this.$http.put('categories/'+this.cateId+'/attributes/'+this.editForm.attr_id,{
                        attr_name:this.editForm.attr_name,
                        attr_sel:this.activeName
                    })
                    if (res.meta.status !== 200) return this.$message.error(res.meta.msg);

                    this.$message.success(res.meta.msg);
                    this.getParamData();
                    this.editDialogVisible=false;
                })
            },

            //根据id删除对应的参数
            async removeParams(attr_id){
                //删除之前弹框询问是否删除
                const confirmResult = await this.$confirm('此操作将永久删除该参数，是否继续？', '提示', {
                    confirmButtonTest: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).catch(error => error)

                //如果用户点了取消按钮返回的是字符串cancle
                //如果用户点击了确定按钮返回的是字符串confirm
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消删除');
                }

                const { data: res } = await this.$http.delete('categories/'+this.cateId+'/attributes/'+attr_id);
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
                this.$message.success(res.meta.msg);
                this.getParamData();
            },

            //文本框失去焦点或按下了enter键都会触发
            async handleInputConfirm(row){
                if(row.inputValue.trim().length===0){
                    row.inputValue='';
                    row.inputVisible=false;
                    return;
                }
               row.attr_vals.push(row.inputValue.trim());
                //发起请求，保存这次操作
                this.saveAttrVals(row);
               row.inputValue='';
               row.inputVisible=false;
            },

            //点击按钮显示文本框
            showInput(row){
                row.inputVisible=true;
                //显示文本框之后自动让文本框自动获取焦点
                //$nextTick犯法的作用，就是当页面元素被重新渲染之后，才会指定回调函数中的代码
                this.$nextTick(_=>{
                    this.$refs.saveTagInput.$refs.input.focus();
                })
            },

            //删除树形象
            handleClose(i,row){
                row.attr_vals.splice(i,1);
                this.saveAttrVals(row);
            },

            //将对attr_vals的操作保存到数据库
            async saveAttrVals(row){
                const { data: res } = await this.$http.put('categories/'+this.cateId+'/attributes/'+row.attr_id,{
                    attr_name:row.attr_name,
                    attr_sel:row.attr_sel,
                    attr_vals:row.attr_vals.join(' ')
                });

                if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
                this.$message.success(res.meta.msg);
            }

        },
        //生命周期 - 创建完成（可以访问当前this实例）
        created() {
            this.getCateList();//获取所有商品分类列表
        },
        //生命周期 - 挂载完成（可以访问DOM元素）
        mounted() {

        },
        beforeCreate() { }, //生命周期 - 创建之前
        beforeMount() { }, //生命周期 - 挂载之前
        beforeUpdate() { }, //生命周期 - 更新之前
        updated() { }, //生命周期 - 更新之后
        beforeDestroy() { }, //生命周期 - 销毁之前
        destroyed() { }, //生命周期 - 销毁完成
        activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
    }
</script>
<style scoped lang='scss'>
    .cat_opt {
        margin: 15px 0;
    }

    .el-cascader {
        width: 30%;
        margin-top: 15px;
    }

    .el-tag{
        margin: 10px;
    }

    .input-new-tag{
        width: 120px;
    }
</style>